package com.ycsj.goldmedalnewconcept.activity;

import android.annotation.TargetApi;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.picasso.Picasso;
import com.ycsj.goldmedalnewconcept.ButtonActivity;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.StartActivity;
import com.ycsj.goldmedalnewconcept.bean.MineBasicInfoResp;
import com.ycsj.goldmedalnewconcept.bean.UserinfoResp;
import com.ycsj.goldmedalnewconcept.bean.mineBasicInfoResp2;
import com.ycsj.goldmedalnewconcept.constant.ConfigConstant;
import com.ycsj.goldmedalnewconcept.constant.Constant;
import com.ycsj.goldmedalnewconcept.constant.NetConstant;
import com.ycsj.goldmedalnewconcept.ui.NotificationServiceUtil;
import com.ycsj.goldmedalnewconcept.utils.BitmapCompressor;
import com.ycsj.goldmedalnewconcept.utils.DataCleanManager;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.utils.SPUtils;
import com.ycsj.goldmedalnewconcept.view.CircleImageView;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import io.rong.imkit.RongIM;

//金牌新概念个人资料
public class MineActivity extends BaseJpStarActivity implements OnClickListener {

	private RelativeLayout uc_question;
	private RelativeLayout rl_mine_score;
	private RelativeLayout rl_mine_cuotiji;
	private RelativeLayout uc_message;
	private RelativeLayout uc_favor;
	private RelativeLayout uc_address;
	private RelativeLayout uc_about;
	private RelativeLayout rl_checkin;
	private TextView tv_checkin;
	private TextView tv_Username;
	private CircleImageView imageView2;
	private String checkin;
	protected static final int CHOOSE_PICTURE = 0;
	protected static final int TAKE_PICTURE = 1;
	private static final int CROP_SMALL_PICTURE = 2;
	protected static Uri tempUri;
	private int mWH = 360;// 单位dp
	private static final int PICTURE_REQUEST_CODE = 444;
	private static final int CAMERA_REQUEST_CODE = 222;
	String filePath = null;
	private TextView textView2;
	private RelativeLayout uc_alert;
	private Calendar cal;
	private RelativeLayout uc_clean;
	private TextView tv_show_cache;
	private ToggleButton tb_alert;
	private Intent intent;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.slidemenu_menu);

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			setTranslucentStatus(true);
		}
		SystemBarTintManager tintManager = new SystemBarTintManager(this);
		tintManager.setStatusBarTintEnabled(true);
		tintManager.setStatusBarTintResource(R.color.base_color);

		init();
		initEvents();

	}

	private void init() {
		rl_mine_score = (RelativeLayout) findViewById(R.id.rl_mine_score);
		rl_mine_cuotiji = (RelativeLayout) findViewById(R.id.rl_mine_cuotiji);
		uc_question = (RelativeLayout) findViewById(R.id.uc_question);
		uc_message = (RelativeLayout) findViewById(R.id.uc_message);
		uc_favor = (RelativeLayout) findViewById(R.id.uc_favor);
		uc_address = (RelativeLayout) findViewById(R.id.uc_address);
		uc_about = (RelativeLayout) findViewById(R.id.uc_about);
		uc_alert = (RelativeLayout) findViewById(R.id.uc_alert);
		uc_clean = (RelativeLayout) findViewById(R.id.uc_clean);
		tv_show_cache = (TextView) findViewById(R.id.tv_show_cache);

		rl_checkin = (RelativeLayout) findViewById(R.id.rl_checkin);
		tv_checkin = (TextView) findViewById(R.id.tv_checkin);
		tv_Username = (TextView) findViewById(R.id.textView1);
		textView2 = (TextView) findViewById(R.id.textView2);
		imageView2 = (CircleImageView) findViewById(R.id.imageView2);
		bt_exit_login = (Button) findViewById(R.id.bt_exit_login);
		tb_alert = (ToggleButton) findViewById(R.id.tb_alert);

		cal = Calendar.getInstance();

		try {
			tv_show_cache.setText(DataCleanManager
					.getTotalCacheSize(MineActivity.this));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		if (SPUtils.getBoolean(MineActivity.this, "alert")) {
			tb_alert.setChecked(true);
		}

	}

	private void initEvents() {
		rl_mine_score.setOnClickListener(this);
		rl_mine_cuotiji.setOnClickListener(this);
		uc_address.setOnClickListener(this);
		uc_favor.setOnClickListener(this);
		uc_question.setOnClickListener(this);
		tv_checkin.setOnClickListener(this);
		uc_about.setOnClickListener(this);
		uc_alert.setOnClickListener(this);
		uc_clean.setOnClickListener(this);

		imageView2.setOnClickListener(this);

		bt_exit_login.setOnClickListener(this);

		tb_alert.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				// TODO Auto-generated method stub
				if (isChecked) {
					SPUtil.putBoolean(MineActivity.this, "alert", isChecked);

					final TimePickerDialog.OnTimeSetListener timeListener = new TimePickerDialog.OnTimeSetListener() {

						@Override
						public void onTimeSet(TimePicker view, int hourOfDay,
								int minute) {
							// TODO Auto-generated method stub
							cal.set(Calendar.HOUR_OF_DAY, hourOfDay);

							cal.set(Calendar.MINUTE, minute);

							SimpleDateFormat dateFormat = new SimpleDateFormat(
									"HH-mm-ss");
							String format = dateFormat.format(new Date());
							String[] split = format.split("-");

							int currHours = Integer.valueOf(split[0]);
							int setHours = Integer.valueOf(hourOfDay);
							int currMinute = Integer.valueOf(split[1]);
							int setMinute = Integer.valueOf(minute);
							int currSec = Integer.valueOf(split[2]);
							if (setHours >= currHours
									&& setMinute >= currMinute) {
								int time3;
								time3 = (setHours - currHours) * 3600
										+ (setMinute - currMinute) * 60
										- Math.abs(currSec);

								// Log.i("test", "three_one" + time3);
								NotificationServiceUtil
										.invokeTimerNotification(
												MineActivity.this,
												Math.abs(time3) * 1000,
												"金牌君,提醒您该学习啦！！！", 1001);

							}
						}
					};

					new TimePickerDialog(MineActivity.this, timeListener,

					cal.get(Calendar.HOUR_OF_DAY),

					cal.get(Calendar.MINUTE), true).show();
				} else {
					NotificationServiceUtil.cancleNotification(
							MineActivity.this, 1001);
					SPUtil.putBoolean(MineActivity.this, "alert", isChecked);
				}
			}
		});
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.rl_mine_score:

			Intent intent1 = new Intent(MineActivity.this,
					ScoreSerchActivity.class);
			startActivity(intent1);
			break;
			
		case R.id.rl_mine_cuotiji:


			if("2".equals(SPUtil.getString(MineActivity.this, "role", ""))){
				intent = new Intent(MineActivity.this,
						ClassListActivity.class);// 选择班级
				intent.putExtra("view_type","9");
			}else{
				intent = new Intent(MineActivity.this,
						CuotijiActivity.class);// 错题集
			}

			startActivity(intent);
			
			break;
			
		case R.id.uc_address:

			Intent intent2 = new Intent(MineActivity.this, ButtonActivity.class);
			startActivity(intent2);
			finish();
			break;
			
		case R.id.uc_favor:
			Intent intent = new Intent(MineActivity.this,
					MineShoucangActivity.class);
			startActivity(intent);
			break;
			
		case R.id.uc_question:
			Uri uri = Uri
					.parse("http://fusion.qq.com/cgi-bin/qzapps/unified_jump?appid=42285754&from=mqq&actionFlag=0&params=pname%3Dcom.ycsj.goldmedalnewconcept%26versioncode%3D1%26channelid%3D%26actionflag%3D0");
			Intent it = new Intent(Intent.ACTION_VIEW, uri);
			startActivity(it);
			break;
			
		case R.id.uc_about:
			Intent intent3 = new Intent(MineActivity.this, AboutActivity.class);
			startActivity(intent3);
			break;

		case R.id.uc_clean:

			try {
				if ("0.0Byte".equals(DataCleanManager
						.getTotalCacheSize(MineActivity.this))) {
					Toast.makeText(MineActivity.this, "没有可清除的缓存！！！",Toast.LENGTH_SHORT).show();
					break;
				}
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			DataCleanManager.clearAllCache(MineActivity.this);
			try {
				tv_show_cache.setText(DataCleanManager
						.getTotalCacheSize(MineActivity.this));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;

		case R.id.uc_alert:
			//

			break;
		case R.id.tv_checkin:
			// 个人信息
			if (!"".equals(SPUtil.getString(MineActivity.this, "account", ""))) {

				Intent intent5 = new Intent(MineActivity.this,
						UserInfoActivity.class);
				startActivity(intent5);
			}

			break;
		case R.id.imageView2:
			if (!"".equals(SPUtil.getString(MineActivity.this, "account", ""))) {

				Intent intent5 = new Intent(MineActivity.this,
						UserInfoActivity.class);
				startActivity(intent5);
			}

			break;

		case R.id.bt_exit_login:

			final Dialog dialog = new Dialog(MineActivity.this,
					R.style.MyDialog);
			// 设置它的ContentView
			dialog.setContentView(R.layout.exit_dialog);
			dialog.setCanceledOnTouchOutside(true);
			Button dialog_button_cancel = (Button) dialog
					.findViewById(R.id.dialog_button_cancel);
			Button dialog_button_ok = (Button) dialog
					.findViewById(R.id.dialog_button_ok);

			dialog_button_cancel.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					dialog.cancel();
				}

			});

			dialog_button_ok.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					SPUtils.put(MineActivity.this, ConfigConstant.IS_LOGIN_ON,
							false);
					SPUtils.put(MineActivity.this, ConfigConstant.USERTOKEN, "");
					SPUtils.put(MineActivity.this, ConfigConstant.USERNAME, "");
					SPUtils.put(MineActivity.this, "Friendlistjson", "");
					SPUtils.put(MineActivity.this, "haveHomeWork", "0");
					SPUtil.putString(getApplicationContext(), "account", "");
					SPUtil.putString(getApplicationContext(), "token1", "");
					SPUtil.putString(getApplicationContext(), "token2", "");
					SPUtil.putString(getApplicationContext(), "name", "");
					SPUtil.putString(getApplicationContext(), "icon", "");
					SPUtil.putString(getApplicationContext(), "role", "");
					SPUtil.putString(getApplicationContext(), "disableGroup",
							"");

					Intent intent5 = new Intent(MineActivity.this,
							StartActivity.class);
					startActivity(intent5);
					RongIM.getInstance().logout();
					dialog.cancel();
					finish();

				}
			});
			dialog.show();
			//
			break;
		default:
			break;
		}

	}

	Bitmap bitmap2headimg = null;

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case TAKE_PICTURE:
				startPhotoZoom(tempUri);
				break;
			case CHOOSE_PICTURE:
				Uri uri = data.getData();
				Bitmap bitmap = null;
				String imgPath = null;
				ContentResolver resolver = this.getContentResolver();
				String[] columns = { MediaStore.Images.Media.DATA };
				Cursor cursor = null;
				cursor = resolver.query(uri, columns, null, null, null);
				imgPath = uri.getPath();
				if (!TextUtils.isEmpty(imgPath) && imgPath.contains(":")) {
					String imgIndex = imgPath.split(":")[1];
					cursor = resolver.query(
							MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
							columns, "_id=?", new String[] { imgIndex }, null);
				}
				if (null != cursor && cursor.moveToFirst()) {
					int columnIndex = cursor.getColumnIndex(columns[0]);
					imgPath = cursor.getString(columnIndex);
					cursor.close();
					String filePath = imgPath;
				}
				if (!TextUtils.isEmpty(imgPath)) {
					bitmap = genBitmap(imgPath);
					bitmap2headimg = genBitmap(imgPath);
					// imageView2.setImageBitmap(bitmap);
					upload();
				}
				break;
			case CROP_SMALL_PICTURE:
				if (data != null) {
					setImageToView(data);
				}
				break;
			}
		}
	}

	/**
	 */
	protected void setImageToView(Intent data) {
		Bundle extras = data.getExtras();
		if (extras != null) {
			Bitmap photo = extras.getParcelable("data");
			imageView2.setImageBitmap(photo);
			try {
				saveFile(photo, "headimg.jpg");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			upload();
		}
	}

	/**
	 * 
	 * @param uri
	 */
	protected void startPhotoZoom(Uri uri) {
		if (uri == null) {
			Log.i("tag", "The uri is not exist.");
		}
		tempUri = uri;
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 150);
		intent.putExtra("outputY", 150);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, CROP_SMALL_PICTURE);
	}

	/** 通过给定的图片路径生成对应的bitmap */
	private Bitmap genBitmap(String imgPath) {
		Options options = new Options();
		// options.inJustDecodeBounds = true;

		// 将图片像素设置为低像素
		options.inDensity = DisplayMetrics.DENSITY_LOW;
		// 降低图片质量 设置为16位
		options.inPreferredConfig = Config.RGB_565;

		BitmapFactory.decodeFile(imgPath, options);
		int imageWidth = options.outWidth;
		int imageHeight = options.outHeight;

		int widthSample = (int) (imageWidth / mWH);
		int heightSample = (int) (imageHeight / mWH);
		// 计算缩放比例
		// options.inSampleSize = widthSample < heightSample ? heightSample
		// : widthSample;
		// options.inSampleSize=2;
		if (imageWidth < 2048 || imageHeight < 2048) {
			options.inSampleSize = 1;
		} else if (imageWidth > 2048 || imageHeight > 2048) {
			options.inSampleSize = 4;
		}
		// options.inJustDecodeBounds = false;
		Bitmap bitmap = BitmapFactory.decodeFile(imgPath, options);
		bitmap = BitmapCompressor.decodeSampledBitmapFromBitmap(bitmap,
				imageWidth / (options.inSampleSize * 5), imageHeight
						/ (options.inSampleSize * 5));

		try {
			saveFile(bitmap, "headimg.jpg");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return bitmap;
	}

	private HttpUtils httpUtils;
	private String url;
	private RequestParams params;

	public void upload() {
		httpUtils = new HttpUtils();
		url = NetConstant.ACCOUNTINFO + "/UserHeadImg.aspx";
		params = new RequestParams();

		params.addBodyParameter("account",
				SPUtils.getString(MineActivity.this, ConfigConstant.USERNAME));
		params.addBodyParameter("usertoken",
				SPUtils.getString(MineActivity.this, ConfigConstant.USERTOKEN));

		String path = getSDPath() + "/goldupload/" + "headimg.jpg";
		File f = new File(path);
		// Log.e("test", "2234" + path);
		String[] split = path.split("\\/");
		String name = split[split.length - 1];
		params.addBodyParameter(name, f);
		params.addBodyParameter("fileinfo", name);

		httpUtils.send(HttpMethod.POST, url, params, callBackHeadimg);
	}

	/**
	 * 保存文件
	 * 
	 * @param bm
	 * @param fileName
	 * @throws IOException
	 */
	public void saveFile(Bitmap bm, String fileName) throws IOException {
		String path = getSDPath() + "/goldupload/";
		File dirFile = new File(path);
		if (!dirFile.exists()) {
			dirFile.mkdir();
		}

		File myCaptureFile = new File(path + fileName);
		BufferedOutputStream bos = new BufferedOutputStream(
				new FileOutputStream(myCaptureFile));
		bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
		bos.flush();
		bos.close();
	}

	public String getSDPath() {
		File sdDir = null;
		boolean sdCardExist = Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
		if (sdCardExist) {
			sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
		} else {
			sdDir = getFilesDir();
		}
		return sdDir.toString();
	}

	public void showNetWorkDialog() {
		Builder builder = new Builder(MineActivity.this);
		builder.setTitle("开启网络服务");
		builder.setMessage("网络没有连接，请到设置进行网络设置！");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				if (Build.VERSION.SDK_INT > 10) {
					// 3.0以上打开设置界面，也可以直接用ACTION_WIRELESS_SETTINGS打开到wifi界面
					startActivity(new Intent(
							android.provider.Settings.ACTION_SETTINGS));
				} else {
					startActivity(new Intent(
							android.provider.Settings.ACTION_WIRELESS_SETTINGS));
				}
				dialog.cancel();
			}
		});

		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});
		builder.show();
	}

	Callback callBackcheckin = new Callback() {

		@Override
		public void onResponse(Response arg0) throws IOException {
			// TODO Auto-generated method stub

		}

		@Override
		public void onFailure(Request arg0, IOException arg1) {
			// TODO Auto-generated method stub

		}
	};

	private RequestCallBack<String> callBackHeadimg = new RequestCallBack<String>() {

		@Override
		public void onSuccess(ResponseInfo<String> responseInfo) {

			String json = responseInfo.result;
			// 使用Gson把json解析成对象
			// 1 得到gson对象
			Gson gson = new Gson();
			// 2 使用gson对象的方法
			// Log.d("test", "上传成功" + json);
			Toast.makeText(MineActivity.this, "上传成功", Toast.LENGTH_SHORT).show();

			SPUtils.put(MineActivity.this, "RongIMNeedRefresh", true);

		}

		@Override
		public void onFailure(HttpException error, String msg) {
			// Toast.makeText(MainActivity.this, "onFailure", 0).show();
			// Log.d("test", "" + error.getMessage());
		}
	};
	Handler handler = new Handler();
	Callback callBackBascinfo = new Callback() {

		@Override
		public void onResponse(Response arg0) throws IOException {
			String json = arg0.body().string();
			// 使用Gson把json解析成对象
			// 1 得到gson对象

			Log.i("test", json.toString());

			Gson gson = new Gson();
			// // 2 使用gson对象的方法
			if ("1".equals(gson.fromJson(json, mineBasicInfoResp2.class).result)
					|| "2".equals(gson.fromJson(json, mineBasicInfoResp2.class).result)) {
				Intent intent = new Intent(MineActivity.this,
						LoginActivity.class);
				startActivity(intent);
				finish();
			} else if ("没查询到用户基本信息".equals(gson.fromJson(json,
					mineBasicInfoResp2.class).result)) {
				Intent intent = new Intent(MineActivity.this,
						LoginActivity.class);
				startActivity(intent);
				finish();
			} else {

				SPUtils.put(MineActivity.this, "BascinfoJson", json);
				final MineBasicInfoResp mineBasicInfoResp = gson.fromJson(json,
						MineBasicInfoResp.class);
				handler.postDelayed(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub

						tv_Username
								.setText(mineBasicInfoResp.username == "" ? "金牌君"
										: mineBasicInfoResp.username);
						checkin = mineBasicInfoResp.checkin;
						tv_checkin.setText(mineBasicInfoResp.checkin);
						if ("未签到".equals(mineBasicInfoResp.checkin)) {
							tv_checkin.setText("签到");
						}
						textView2.setText(SPUtils.getString(MineActivity.this,
								ConfigConstant.USERNAME));
						// Transformation transformation = new
						// RoundedTransformationBuilder()
						// .borderColor(0xffFF870C).borderWidthDp(0)
						// .cornerRadiusDp(85).oval(true).build();

						if ("".equals(mineBasicInfoResp.headerimg)) {
							Picasso.with(MineActivity.this)
									.load(R.drawable.xuesheng).fit()
									.into(imageView2);
						} else {

							Picasso.with(MineActivity.this)
									.load(mineBasicInfoResp.headerimg)
									.resize(50, 50).centerCrop()
									.error(R.drawable.xuesheng)
									.into(imageView2);
						}

						if (bitmap2headimg != null) {
							imageView2.setImageBitmap(bitmap2headimg);
						}
					}
				}, 10);
			}

		}

		@Override
		public void onFailure(Request arg0, IOException arg1) {
			// TODO Auto-generated method stub

		}
	};
	private Button bt_exit_login;

	@TargetApi(19)
	private void setTranslucentStatus(boolean on) {
		Window win = getWindow();
		WindowManager.LayoutParams winParams = win.getAttributes();
		final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
		if (on) {
			winParams.flags |= bits;
		} else {
			winParams.flags &= ~bits;
		}
		win.setAttributes(winParams);
	}

	protected void showChoosePicDialog() {
		Builder builder = new Builder(this);
		builder.setTitle("设置头像");
		String[] items = { "选择本地图片", "拍照" };
		builder.setNegativeButton("取消", null);
		builder.setItems(items, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
				case CHOOSE_PICTURE:
					Intent openAlbumIntent = new Intent(
							Intent.ACTION_GET_CONTENT);
					openAlbumIntent.setType("image/*");
					startActivityForResult(openAlbumIntent, CHOOSE_PICTURE);
					break;

				case TAKE_PICTURE:
					Intent openCameraIntent = new Intent(
							MediaStore.ACTION_IMAGE_CAPTURE);
					tempUri = Uri.fromFile(new File(Environment
							.getExternalStorageDirectory(), "image.jpg"));
					openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
					startActivityForResult(openCameraIntent, TAKE_PICTURE);
					break;
				}
			}
		});
		builder.create().show();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		OkHttpClient mOkHttpClient = new OkHttpClient();
		FormEncodingBuilder builder = new FormEncodingBuilder();
		builder.add("type", "5");
		builder.add("c", SPUtil.getString(MineActivity.this, "account", ""));
		builder.add("role", SPUtil.getString(MineActivity.this, "role", ""));
		builder.add("platform", "2");
		Request request = new Request.Builder()
				.url(Constant.SERVER_URL + "AccountMsg").post(builder.build())
				.build();
		mOkHttpClient.newCall(request).enqueue(callBack);
	}

	Handler handler1 = new Handler();
	Callback callBack = new Callback() {

		@Override
		public void onFailure(Request arg0, IOException arg1) {

		}

		@Override
		public void onResponse(Response arg0) throws IOException {
			String json = arg0.body().string();
			Log.e("test", json);
			Gson gson = new Gson();
			final UserinfoResp fromJson = gson.fromJson(json,
					UserinfoResp.class);
			handler1.postDelayed(new Runnable() {

				@Override
				public void run() {
					if (fromJson == null || fromJson.name == null
							|| "".equals(fromJson.name)) {
						tv_Username.setText("请退出登录");

					} else {
						tv_Username.setText(fromJson.name);
						textView2.setText(fromJson.user_id);

						Picasso.with(MineActivity.this).load(fromJson.icon)
								.error(R.drawable.header).into(imageView2);
					}
				}
			}, 100);

		}

	};

}
